package com.org.redis.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 可重入锁
 * @author wang
 */
public class RLock implements Lock {

    AtomicInteger state = new AtomicInteger();

    private boolean isLocked = false;

    Thread ownerThread = null;

    int count = 0;

    @Override
    public synchronized void lock() {
        Thread currentThread = Thread.currentThread();
        while (isLocked && ownerThread != currentThread){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isLocked = true;
        count++;
        ownerThread = currentThread;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public synchronized void unlock() {
        Thread currentThread = Thread.currentThread();
        if(ownerThread != ownerThread){
            return;
        }
        count--;
        if(count == 0){
            isLocked = false;
            notify();
        }
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
